package com.smart.community.region.service.impl;

import java.time.LocalDateTime;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.Objects;
import java.util.stream.Collectors;

import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.smart.community.commons.cache.DataScopeInfo;
import com.smart.community.commons.utils.SecurityUtils;
import com.smart.community.commons.exception.BusinessException;
import com.smart.community.commons.result.PageResult;
import com.smart.community.commons.result.Result;
import com.smart.community.commons.utils.SecurityUtils;
import com.smart.community.commons.utils.StringUtils;
import com.smart.community.feign.property.service.DataScopeFeign;
import com.smart.community.region.dto.UnitDTO;
import com.smart.community.region.dto.UnitQueryDTO;
import com.smart.community.region.entity.Building;
import com.smart.community.region.entity.Household;
import com.smart.community.region.entity.Unit;
import com.smart.community.region.mapper.BuildingMapper;
import com.smart.community.region.mapper.HouseholdMapper;
import com.smart.community.region.mapper.UnitMapper;
import com.smart.community.region.service.CommunityCacheService;
import com.smart.community.region.service.IUnitService;
import com.smart.community.region.vo.CommunityVO;
import com.smart.community.region.vo.UnitVO;
import com.smart.community.region.vo.UnitDeleteImpactVO;

import io.seata.spring.annotation.GlobalTransactional;
import lombok.extern.slf4j.Slf4j;

/**
 * 单元楼管理服务实现类
 *
 * @author Wu.Liang
 * @since 2024-12-21
 */
@Slf4j
@Service
public class UnitServiceImpl extends ServiceImpl<UnitMapper, Unit> implements IUnitService {

    @Autowired
    private BuildingMapper buildingMapper;
    
    @Autowired
    private DataScopeFeign dataScopeFeign;

    @Autowired
    private CommunityCacheService communityCacheService;
    
    // 暂时注释掉其他服务依赖，专注于核心删除功能
    // @Autowired
    // private IHouseholdService householdService;
    // @Autowired
    // private IResidentService residentService;
    // @Autowired
    // private IPropertyFeeService propertyFeeService;
    // @Autowired
    // private ISanitationFeeService sanitationFeeService;


    @Override
    public PageResult<UnitVO> getUnitPage(UnitQueryDTO queryDTO) {
        log.info("分页查询单元楼列表，查询条件：{}", queryDTO);
        
        try {
            // 构建查询条件
            LambdaQueryWrapper<Unit> queryWrapper = new LambdaQueryWrapper<>();
            
            // 单元名称模糊查询
            if (StringUtils.isNotBlank(queryDTO.getUnitName())) {
                queryWrapper.like(Unit::getUnitName, queryDTO.getUnitName());
            }
            
            // 单元编码模糊查询
            if (StringUtils.isNotBlank(queryDTO.getUnitCode())) {
                queryWrapper.like(Unit::getUnitCode, queryDTO.getUnitCode());
            }
            
            // 楼栋ID查询
            if (queryDTO.getBuildingId() != null) {
                queryWrapper.eq(Unit::getBuildingId, queryDTO.getBuildingId());
            }
            
            // 社区ID查询 - 根据社区ID查询该社区下所有楼栋的单元
            if (queryDTO.getCommunityId() != null) {
                // 先查询该社区下的所有楼栋ID
                List<Long> buildingIds = getBuildingIdsByCommunityId(queryDTO.getCommunityId());
                if (buildingIds.isEmpty()) {
                    // 如果该社区下没有楼栋，直接返回空结果
                    return new PageResult<>(queryDTO.getCurrent(), queryDTO.getSize(), 0L, new ArrayList<>());
                }
                queryWrapper.in(Unit::getBuildingId, buildingIds);
            }
            
            // 状态查询
            if (queryDTO.getStatus() != null) {
                queryWrapper.eq(Unit::getStatus, queryDTO.getStatus());
            }
            
            // 应用数据权限过滤
            applyDataPermissionFilter(queryWrapper);
            
            // 排序
            queryWrapper.orderByDesc(Unit::getSortOrder, Unit::getCreateTime);
            
            // 分页查询
            Page<Unit> page = new Page<>(queryDTO.getCurrent(), queryDTO.getSize());
            IPage<Unit> unitPage = this.page(page, queryWrapper);
            
            // 转换为VO
            List<UnitVO> unitVOList = convertToVOList(unitPage.getRecords());
            
            return new PageResult<>(queryDTO.getCurrent(), queryDTO.getSize(),
                    unitPage.getTotal(), unitVOList);
            
        } catch (Exception e) {
            log.error("分页查询单元楼列表失败", e);
            throw new BusinessException("查询单元楼列表失败：" + e.getMessage());
        }
    }

    @Override
    public List<UnitVO> getUnitList(UnitQueryDTO queryDTO) {
        log.info("查询单元楼列表，查询条件：{}", queryDTO);
        
        try {
            // 构建查询条件
            LambdaQueryWrapper<Unit> queryWrapper = new LambdaQueryWrapper<>();
            
            // 单元名称模糊查询
            if (StringUtils.isNotBlank(queryDTO.getUnitName())) {
                queryWrapper.like(Unit::getUnitName, queryDTO.getUnitName());
            }
            
            // 单元编码模糊查询
            if (StringUtils.isNotBlank(queryDTO.getUnitCode())) {
                queryWrapper.like(Unit::getUnitCode, queryDTO.getUnitCode());
            }
            
            // 楼栋ID查询
            if (queryDTO.getBuildingId() != null) {
                queryWrapper.eq(Unit::getBuildingId, queryDTO.getBuildingId());
            }
            
            // 状态查询
            if (queryDTO.getStatus() != null) {
                queryWrapper.eq(Unit::getStatus, queryDTO.getStatus());
            }
            
            // 排序
            queryWrapper.orderByAsc(Unit::getSortOrder, Unit::getCreateTime);
            
            // 查询
            List<Unit> unitList = this.list(queryWrapper);
            
            // 转换为VO
            return convertToVOList(unitList);
                    
        } catch (Exception e) {
            log.error("查询单元楼列表失败", e);
            throw new BusinessException("查询单元楼列表失败：" + e.getMessage());
        }
    }

    @Override
    public UnitVO getUnitById(Long unitId) {
        log.info("根据ID查询单元楼，单元楼ID：{}", unitId);
        
        try {
            Unit unit = this.getById(unitId);
            if (unit == null) {
                throw new BusinessException("单元楼不存在");
            }
            
            return convertToVO(unit);
            
        } catch (Exception e) {
            log.error("根据ID查询单元楼失败，单元楼ID：{}", unitId, e);
            throw new BusinessException("查询单元楼失败：" + e.getMessage());
        }
    }

    @Override
    public UnitVO getUnitByCode(String unitCode) {
        log.info("根据编码查询单元楼，单元楼编码：{}", unitCode);
        
        try {
            Unit unit = baseMapper.selectByUnitCode(unitCode);
            if (unit == null) {
                throw new BusinessException("单元楼不存在");
            }
            
            return convertToVO(unit);
            
        } catch (Exception e) {
            log.error("根据编码查询单元楼失败，单元楼编码：{}", unitCode, e);
            throw new BusinessException("查询单元楼失败：" + e.getMessage());
        }
    }

    @Override
    @GlobalTransactional(rollbackFor = Exception.class)
    public Result<UnitVO> addUnit(UnitDTO unitDTO) {
        log.info("新增单元楼，单元楼信息：{}", unitDTO);
        
        try {
            // 参数校验
            validateUnitDTO(unitDTO);
            
            // 检查单元编码是否已存在
            if (baseMapper.existsByUnitCode(unitDTO.getUnitCode(), null)) {
                throw new BusinessException("单元编码已存在");
            }
            
            // 检查楼栋是否存在
            if (unitDTO.getBuildingId() != null) {
                Building building = buildingMapper.selectById(unitDTO.getBuildingId());
                if (building == null) {
                    throw new BusinessException("楼栋不存在");
                }
            }
            
            // 构建单元楼实体
            Unit unit = new Unit();
            BeanUtils.copyProperties(unitDTO, unit);
            
            // 设置创建信息
            Long userId = SecurityUtils.getCurrentUserId();
            if (userId == null) {
                throw new BusinessException("获取当前用户信息失败");
            }
            unit.setCreateBy(userId);
            unit.setCreateTime(LocalDateTime.now());
            unit.setUpdateBy(userId);
            unit.setUpdateTime(LocalDateTime.now());
            
            // 保存单元楼
            boolean success = this.save(unit);
            if (!success) {
                throw new BusinessException("保存单元楼失败");
            }
            
            log.info("新增单元楼成功，单元楼ID：{}", unit.getId());
            return Result.success("新增单元楼成功", convertToVO(unit));
            
        } catch (Exception e) {
            log.error("新增单元楼失败", e);
            throw new BusinessException("新增单元楼失败：" + e.getMessage());
        }
    }

    @Override
    @GlobalTransactional(rollbackFor = Exception.class)
    public Result<UnitVO> updateUnit(UnitDTO unitDTO) {
        log.info("更新单元楼，单元楼信息：{}", unitDTO);
        
        try {
            // 参数校验
            if (unitDTO.getId() == null) {
                throw new BusinessException("单元楼ID不能为空");
            }
            validateUnitDTO(unitDTO);
            
            // 检查单元楼是否存在
            Unit existingUnit = this.getById(unitDTO.getId());
            if (existingUnit == null) {
                throw new BusinessException("单元楼不存在");
            }
            
            // 检查单元编码是否已存在（排除当前单元楼）
            if (baseMapper.existsByUnitCode(unitDTO.getUnitCode(), unitDTO.getId())) {
                throw new BusinessException("单元编码已存在");
            }
            
            // 检查楼栋是否存在
            if (unitDTO.getBuildingId() != null) {
                Building building = buildingMapper.selectById(unitDTO.getBuildingId());
                if (building == null) {
                    throw new BusinessException("楼栋不存在");
                }
            }
            
            // 更新单元楼信息 - 保留原始版本号以确保乐观锁正常工作
            BeanUtils.copyProperties(unitDTO, existingUnit);
            
            // 设置更新信息
            Long userId = SecurityUtils.getCurrentUserId();
            if (userId == null) {
                throw new BusinessException("获取当前用户信息失败");
            }
            existingUnit.setUpdateBy(userId);
            existingUnit.setUpdateTime(LocalDateTime.now());
            
            // 更新单元楼
            boolean success = this.updateById(existingUnit);
            if (!success) {
                throw new BusinessException("更新单元楼失败");
            }
            
            log.info("更新单元楼成功，单元楼ID：{}", existingUnit.getId());
            return Result.success("更新单元楼成功", convertToVO(existingUnit));
            
        } catch (Exception e) {
            log.error("更新单元楼失败", e);
            throw new BusinessException("更新单元楼失败：" + e.getMessage());
        }
    }

    @Override
    @GlobalTransactional(rollbackFor = Exception.class)
    public Result<Void> deleteUnit(Long unitId) {
        log.info("删除单元楼，单元楼ID：{}", unitId);
        
        try {
            // 检查单元楼是否存在
            Unit unit = this.getById(unitId);
            if (unit == null) {
                throw new BusinessException("单元楼不存在");
            }
            
            // 检查是否有住户
            // TODO: 这里需要检查住户表，暂时跳过
            
            // 删除单元楼
            boolean success = this.removeById(unitId);
            if (!success) {
                throw new BusinessException("删除单元楼失败");
            }
            
            log.info("删除单元楼成功，单元楼ID：{}", unitId);
            return Result.success();
            
        } catch (Exception e) {
            log.error("删除单元楼失败，单元楼ID：{}", unitId, e);
            throw new BusinessException("删除单元楼失败：" + e.getMessage());
        }
    }

    @Override
    @GlobalTransactional(rollbackFor = Exception.class)
    public Result<Void> batchDeleteUnit(List<Long> unitIds) {
        log.info("批量删除单元楼，单元楼ID列表：{}", unitIds);
        
        try {
            if (unitIds == null || unitIds.isEmpty()) {
                throw new BusinessException("单元楼ID列表不能为空");
            }
            
            // 检查是否有住户
            // TODO: 这里需要检查住户表，暂时跳过
            
            // 批量删除单元楼
            boolean success = this.removeByIds(unitIds);
            if (!success) {
                throw new BusinessException("批量删除单元楼失败");
            }
            
            log.info("批量删除单元楼成功，删除数量：{}", unitIds.size());
            return Result.success();
            
        } catch (Exception e) {
            log.error("批量删除单元楼失败", e);
            throw new BusinessException("批量删除单元楼失败：" + e.getMessage());
        }
    }

    @Override
    public List<UnitVO> getUnitByBuildingId(Long buildingId) {
        log.info("根据楼栋ID查询单元楼列表，楼栋ID：{}", buildingId);
        
        try {
            List<Unit> unitList = baseMapper.selectByBuildingId(buildingId);
            
            return unitList.stream()
                    .map(this::convertToVO)
                    .collect(Collectors.toList());
                    
        } catch (Exception e) {
            log.error("根据楼栋ID查询单元楼列表失败，楼栋ID：{}", buildingId, e);
            throw new BusinessException("查询单元楼列表失败：" + e.getMessage());
        }
    }

    @Override
    public List<Unit> getUnitsByBuildingId(Long buildingId) {
        log.info("根据楼栋ID获取单元列表，楼栋ID：{}", buildingId);
        
        try {
            LambdaQueryWrapper<Unit> queryWrapper = new LambdaQueryWrapper<>();
            queryWrapper.eq(Unit::getBuildingId, buildingId)
                    .orderByAsc(Unit::getSortOrder, Unit::getCreateTime);
            
            return this.list(queryWrapper);
                    
        } catch (Exception e) {
            log.error("根据楼栋ID获取单元列表失败，楼栋ID：{}", buildingId, e);
            throw new BusinessException("获取单元列表失败：" + e.getMessage());
        }
    }

    @Override
    public boolean checkUnitCodeUnique(String unitCode, Long excludeUnitId) {
        log.info("检查单元楼编码唯一性，单元楼编码：{}，排除单元楼ID：{}", unitCode, excludeUnitId);
        
        try {
            return !baseMapper.existsByUnitCode(unitCode, excludeUnitId);
            
        } catch (Exception e) {
            log.error("检查单元楼编码唯一性失败", e);
            throw new BusinessException("检查单元楼编码唯一性失败：" + e.getMessage());
        }
    }

    @Override
    public boolean existsByUnitCode(String unitCode, Long excludeId) {
        log.info("检查单元编码是否存在，单元编码：{}，排除ID：{}", unitCode, excludeId);
        
        try {
            return baseMapper.existsByUnitCode(unitCode, excludeId);
            
        } catch (Exception e) {
            log.error("检查单元编码是否存在失败", e);
            throw new BusinessException("检查单元编码是否存在失败：" + e.getMessage());
        }
    }

    @Override
    public Long countUnits(Long buildingId) {
        log.info("统计单元数量，楼栋ID：{}", buildingId);
        
        try {
            LambdaQueryWrapper<Unit> queryWrapper = new LambdaQueryWrapper<>();
            queryWrapper.eq(Unit::getDeleted, 0);
            
            if (buildingId != null) {
                queryWrapper.eq(Unit::getBuildingId, buildingId);
            }
            
            return Long.valueOf(this.count(queryWrapper));
            
        } catch (Exception e) {
            log.error("统计单元数量失败，楼栋ID：{}", buildingId, e);
            throw new BusinessException("统计单元数量失败：" + e.getMessage());
        }
    }

    @Override
    public void clearUnitCache(Long unitId) {
        log.info("清除单元缓存，单元ID：{}", unitId);
        
        try {
            // TODO: 实现缓存清除逻辑
            // RedisTemplate.delete("unit:" + unitId);
            // RedisTemplate.delete("unit:list:*");
            
        } catch (Exception e) {
            log.error("清除单元缓存失败，单元ID：{}", unitId, e);
        }
    }

    @Override
    public void clearAllUnitCache() {
        log.info("清除所有单元缓存");
        
        try {
            // TODO: 实现缓存清除逻辑
            // RedisTemplate.delete("unit:*");
            
        } catch (Exception e) {
            log.error("清除所有单元缓存失败", e);
        }
    }

    @Override
    public Object getUnitStats(Long unitId) {
        log.info("获取单元统计信息，单元ID：{}", unitId);
        
        try {
            Unit unit = this.getById(unitId);
            if (unit == null) {
                throw new BusinessException("单元不存在");
            }
            
            // 构建统计信息
            Map<String, Object> stats = new HashMap<>();
            stats.put("unitId", unitId);
            stats.put("unitName", unit.getUnitName());
            stats.put("unitCode", unit.getUnitCode());
            stats.put("status", unit.getStatus());
            
            return stats;
            
        } catch (Exception e) {
            log.error("获取单元统计信息失败，单元ID：{}", unitId, e);
            throw new BusinessException("获取单元统计信息失败：" + e.getMessage());
        }
    }

    @Autowired
    private HouseholdMapper householdMapper;

    @Override
    public List<Object> getHouseholdsByUnit(Long unitId) {
        log.info("获取单元下的房户列表，单元ID：{}", unitId);
        
        try {
            if (unitId == null) {
                return new ArrayList<>();
            }
            
            // 查询指定单元下的所有房户
            LambdaQueryWrapper<Household> queryWrapper = new LambdaQueryWrapper<>();
            queryWrapper.eq(Household::getUnitId, unitId)
                       .orderByDesc(Household::getRoomNumber);
            
            List<Household> households = householdMapper.selectList(queryWrapper);
            
            // 转换为前端需要的格式
            List<Object> result = households.stream()
                .map(household -> {
                    Map<String, Object> householdMap = new HashMap<>();
                    householdMap.put("id", household.getId());
                    householdMap.put("roomNumber", household.getRoomNumber());
                    householdMap.put("householdCode", household.getHouseholdCode());
                    householdMap.put("buildingId", household.getBuildingId());
                    householdMap.put("unitId", household.getUnitId());
                    householdMap.put("floorNumber", household.getFloorNumber());
                    householdMap.put("roomType", household.getRoomType());
                    householdMap.put("area", household.getArea());
                    householdMap.put("usableArea", household.getUsableArea());
                    householdMap.put("orientation", household.getOrientation());
                    householdMap.put("ownerName", ""); // TODO: 从住户表获取业主姓名
                    householdMap.put("ownerPhone", ""); // TODO: 从住户表获取业主电话
                    householdMap.put("propertyType", household.getPropertyType());
                    householdMap.put("status", household.getStatus());
                    return householdMap;
                })
                .collect(Collectors.toList());
            
            log.info("获取单元下的房户列表成功，单元ID：{}，房户数量：{}", unitId, result.size());
            return result;
            
        } catch (Exception e) {
            log.error("获取单元下的房户列表失败，单元ID：{}", unitId, e);
            throw new BusinessException("获取房户列表失败：" + e.getMessage());
        }
    }

    @Override
    public List<Unit> getUnitsByCommunityIds(List<Long> communityIds, List<Long> buildingIds) {
        log.info("根据社区ID集合查询单元列表，社区ID列表：{}，楼栋ID列表：{}", communityIds, buildingIds);
        
        try {
            // TODO: 实现根据社区ID查询单元列表逻辑
            return new ArrayList<>();
            
        } catch (Exception e) {
            log.error("根据社区ID集合查询单元列表失败", e);
            throw new BusinessException("查询单元列表失败：" + e.getMessage());
        }
    }

    @Override
    public Map<Long, List<Unit>> getUnitsGroupedByBuilding(List<Long> communityIds, List<Long> buildingIds) {
        log.info("根据社区ID集合查询单元，按楼栋分组返回，社区ID列表：{}，楼栋ID列表：{}", communityIds, buildingIds);
        
        try {
            // TODO: 实现按楼栋分组查询单元逻辑
            return new HashMap<>();
            
        } catch (Exception e) {
            log.error("根据社区ID集合查询单元，按楼栋分组返回失败", e);
            throw new BusinessException("查询单元列表失败：" + e.getMessage());
        }
    }

    @Override
    public List<Unit> getUnitsByUserPermission(Long userId) {
        log.info("根据用户权限获取单元列表，用户ID：{}", userId);
        
        try {
            // TODO: 实现根据用户权限查询单元列表逻辑
            return new ArrayList<>();
            
        } catch (Exception e) {
            log.error("根据用户权限获取单元列表失败，用户ID：{}", userId, e);
            throw new BusinessException("获取单元列表失败：" + e.getMessage());
        }
    }

    @Override
    public boolean updateUnitStatus(Long unitId, Integer status) {
        log.info("更新单元状态，单元ID：{}，状态：{}", unitId, status);
        
        try {
            Unit unit = this.getById(unitId);
            if (unit == null) {
                throw new BusinessException("单元不存在");
            }
            
            unit.setStatus(status);
            unit.setUpdateTime(LocalDateTime.now());
            
            boolean result = this.updateById(unit);
            if (result) {
                log.info("更新单元状态成功，单元ID：{}，状态：{}", unitId, status);
                clearUnitCache(unitId);
            }
            
            return result;
            
        } catch (Exception e) {
            log.error("更新单元状态失败，单元ID：{}，状态：{}", unitId, status, e);
            throw new BusinessException("更新单元状态失败：" + e.getMessage());
        }
    }

    @Override
    public boolean batchUpdateUnitStatus(List<Long> unitIds, Integer status) {
        log.info("批量更新单元状态，单元ID列表：{}，状态：{}", unitIds, status);
        
        try {
            if (unitIds == null || unitIds.isEmpty()) {
                throw new BusinessException("单元ID列表不能为空");
            }
            
            List<Unit> units = this.listByIds(unitIds);
            if (units.size() != unitIds.size()) {
                throw new BusinessException("部分单元不存在");
            }
            
            for (Unit unit : units) {
                unit.setStatus(status);
                unit.setUpdateTime(LocalDateTime.now());
            }
            
            boolean result = this.updateBatchById(units);
            if (result) {
                log.info("批量更新单元状态成功，单元ID列表：{}，状态：{}", unitIds, status);
                for (Long unitId : unitIds) {
                    clearUnitCache(unitId);
                }
            }
            
            return result;
            
        } catch (Exception e) {
            log.error("批量更新单元状态失败", e);
            throw new BusinessException("批量更新单元状态失败：" + e.getMessage());
        }
    }

    @Override
    public String deleteUnitWithRelations(Long unitId, Long currentUserId) throws BusinessException {
        log.info("开始删除单元，单元ID：{}，当前用户ID：{}", unitId, currentUserId);

        // 1. 权限验证
        validateDeletePermission(unitId, currentUserId);

        // 2. 检查单元是否存在
        Unit unit = this.getById(unitId);
        if (unit == null) {
            throw new BusinessException("单元不存在");
        }

        // 3. 检查删除影响（暂时简化）
        // UnitDeleteImpactVO impact = checkDeleteImpact(unitId);
        // if (impact.getTotalRelatedCount() > 0) {
        //     log.warn("单元存在关联数据，单元ID：{}，关联数据：{}", unitId, impact);
        //     throw new BusinessException("单元存在关联数据，无法直接删除。关联数据：" + impact.getSummary());
        // }

        // 4. 执行删除操作
        boolean success = this.removeById(unitId);
        if (!success) {
            throw new BusinessException("删除单元失败");
        }

        log.info("删除单元成功，单元ID：{}，单元名称：{}", unitId, unit.getUnitName());
        return "删除单元成功：" + unit.getUnitName();
    }

    @Override
    public String batchDeleteUnitsWithRelations(List<Long> unitIds, Long currentUserId) throws BusinessException {
        log.info("开始批量删除单元，单元ID列表：{}，当前用户ID：{}", unitIds, currentUserId);

        if (unitIds == null || unitIds.isEmpty()) {
            throw new BusinessException("单元ID列表不能为空");
        }

        List<String> successList = new ArrayList<>();
        List<String> failList = new ArrayList<>();

        for (Long unitId : unitIds) {
            try {
                String result = deleteUnitWithRelations(unitId, currentUserId);
                successList.add("单元ID " + unitId + "：" + result);
            } catch (Exception e) {
                log.error("删除单元失败，单元ID：{}", unitId, e);
                failList.add("单元ID " + unitId + "：" + e.getMessage());
            }
        }

        // 构建结果信息
        StringBuilder result = new StringBuilder();
        if (!successList.isEmpty()) {
            result.append("成功删除：").append(successList.size()).append("个单元\n");
            successList.forEach(s -> result.append(s).append("\n"));
        }
        if (!failList.isEmpty()) {
            result.append("删除失败：").append(failList.size()).append("个单元\n");
            failList.forEach(s -> result.append(s).append("\n"));
        }

        log.info("批量删除单元完成，成功：{}个，失败：{}个", successList.size(), failList.size());
        return result.toString();
    }

    @Override
    public UnitDeleteImpactVO checkDeleteImpact(Long unitId) {
        log.info("检查单元删除影响，单元ID：{}", unitId);
        
        // 暂时返回空的影响分析，后续完善
        UnitDeleteImpactVO impact = new UnitDeleteImpactVO();
        impact.setUnitId(unitId);
        impact.setHouseholdCount(0L);
        impact.setResidentRelationCount(0L);
        impact.setPropertyFeeCount(0L);
        impact.setSanitationFeeCount(0L);
        impact.setTotalRelatedCount(0L);
        impact.setSummary("无关联数据");
        
        log.info("单元删除影响检查完成，单元ID：{}，关联数据总数：0", unitId);
        return impact;
    }

    @Override
    public List<UnitVO> getUnitListByBuilding(Long buildingId) {
        log.info("根据楼栋ID获取单元列表，楼栋ID：{}", buildingId);

        List<Unit> units = this.list(new LambdaQueryWrapper<Unit>()
                .eq(Unit::getBuildingId, buildingId)
                .eq(Unit::getDeleted, 0)
                .orderByAsc(Unit::getUnitName));

        return units.stream()
                .map(this::convertToVO)
                .collect(Collectors.toList());
    }

    /**
     * 验证删除权限
     */
    private void validateDeletePermission(Long unitId, Long currentUserId) throws BusinessException {
        try {
            // 1. 获取单元信息
            Unit unit = this.getById(unitId);
            if (unit == null) {
                throw new BusinessException("单元不存在");
            }

            // 2. 检查超级管理员权限
            Boolean isSuperAdmin = dataScopeFeign.isUserSuperAdmin(currentUserId);
            if (isSuperAdmin) {
                return;
            }

            // 3. 获取用户数据权限范围
            List<Long> authorizedCommunityIds = dataScopeFeign.getUserCommunityIds(currentUserId);
            if (!authorizedCommunityIds.contains(unit.getCommunityId())) {
                throw new BusinessException("无权限删除该单元");
            }
        } catch (Exception e) {
            log.error("权限验证失败，单元ID：{}，用户ID：{}", unitId, currentUserId, e);
            throw new BusinessException("权限验证失败：" + e.getMessage());
        }
    }

    /**
     * 生成影响摘要
     */
    private String generateImpactSummary(UnitDeleteImpactVO impact) {
        List<String> items = new ArrayList<>();
        
        if (impact.getHouseholdCount() > 0) {
            items.add(impact.getHouseholdCount() + "个房户");
        }
        if (impact.getResidentRelationCount() > 0) {
            items.add(impact.getResidentRelationCount() + "个住户关联");
        }
        if (impact.getPropertyFeeCount() > 0) {
            items.add(impact.getPropertyFeeCount() + "条物业费记录");
        }
        if (impact.getSanitationFeeCount() > 0) {
            items.add(impact.getSanitationFeeCount() + "条卫生费记录");
        }

        if (items.isEmpty()) {
            return "无关联数据";
        } else {
            return String.join("、", items);
        }
    }

    /**
     * 转换为VO
     */
    private UnitVO convertToVO(Unit unit) {
        if (unit == null) {
            return null;
        }
        
        UnitVO unitVO = new UnitVO();
        BeanUtils.copyProperties(unit, unitVO);
        
        // 设置楼栋名称
        if (unit.getBuildingId() != null) {
            try {
                Building building = buildingMapper.selectById(unit.getBuildingId());
                if (building != null) {
                    unitVO.setBuildingName(building.getBuildingName());
                    
                    // 同时设置社区名称（如果UnitVO有communityName字段的话）
                    if (building.getCommunityId() != null) {
                        CommunityVO community = communityCacheService.getCommunityById(building.getCommunityId());
                        if (community != null) {
                            unitVO.setCommunityId(building.getCommunityId());
                            unitVO.setCommunityName(community.getCommunityName());
                        }
                    }
                }
            } catch (Exception e) {
                log.warn("获取楼栋信息失败，楼栋ID：{}", unit.getBuildingId(), e);
                unitVO.setBuildingName("未知楼栋");
            }
        }
        
        return unitVO;
    }

    /**
     * 批量转换为VO对象（优化版本，使用批量缓存查询）
     */
    public List<UnitVO> convertToVOList(List<Unit> units) {
        if (units == null || units.isEmpty()) {
            return new ArrayList<>();
        }

        // 收集所有楼栋ID
        List<Long> buildingIds = units.stream()
                .map(Unit::getBuildingId)
                .filter(Objects::nonNull)
                .distinct()
                .collect(Collectors.toList());

        // 批量获取楼栋信息
        Map<Long, Building> buildingMap = new HashMap<>();
        if (!buildingIds.isEmpty()) {
            try {
                List<Building> buildings = buildingMapper.selectBatchIds(buildingIds);
                buildingMap = buildings.stream()
                        .collect(Collectors.toMap(Building::getId, building -> building));
            } catch (Exception e) {
                log.warn("批量获取楼栋信息失败", e);
            }
        }

        // 收集所有社区ID
        List<Long> communityIds = buildingMap.values().stream()
                .map(Building::getCommunityId)
                .filter(Objects::nonNull)
                .distinct()
                .collect(Collectors.toList());

        // 批量获取社区信息
        Map<Long, CommunityVO> communityMap = new HashMap<>();
        if (!communityIds.isEmpty()) {
            try {
                communityMap = communityCacheService.getCommunitiesByIds(communityIds);
            } catch (Exception e) {
                log.warn("批量获取社区信息失败", e);
            }
        }

        // 转换为VO
        final Map<Long, Building> finalBuildingMap = buildingMap;
        final Map<Long, CommunityVO> finalCommunityMap = communityMap;
        return units.stream().map(unit -> {
            UnitVO vo = new UnitVO();
            BeanUtils.copyProperties(unit, vo);
            
            // 填充楼栋名称和社区信息
            if (unit.getBuildingId() != null) {
                Building building = finalBuildingMap.get(unit.getBuildingId());
                if (building != null) {
                    vo.setBuildingName(building.getBuildingName());
                    
                    // 填充社区信息
                    if (building.getCommunityId() != null) {
                        CommunityVO community = finalCommunityMap.get(building.getCommunityId());
                        if (community != null) {
                            vo.setCommunityId(building.getCommunityId());
                            vo.setCommunityName(community.getCommunityName());
                        }
                    }
                } else {
                    vo.setBuildingName("未知楼栋");
                }
            }
            
            return vo;
        }).collect(Collectors.toList());
    }

    /**
     * 参数校验
     */
    private void validateUnitDTO(UnitDTO unitDTO) {
        if (unitDTO == null) {
            throw new BusinessException("单元楼信息不能为空");
        }
        
        if (StringUtils.isBlank(unitDTO.getUnitName())) {
            throw new BusinessException("单元楼名称不能为空");
        }
        
        if (StringUtils.isBlank(unitDTO.getUnitCode())) {
            throw new BusinessException("单元楼编码不能为空");
        }
        
        if (unitDTO.getBuildingId() == null) {
            throw new BusinessException("楼栋ID不能为空");
        }
        
        if (unitDTO.getStatus() == null) {
            throw new BusinessException("单元楼状态不能为空");
        }
    }

    // ==================== 数据权限业务接口实现 ====================

    @Override
    public List<Long> getUnitIdsByBuildingIds(List<Long> buildingIds) {
        log.info("根据楼栋ID集合获取单元ID集合，楼栋数量：{}", buildingIds != null ? buildingIds.size() : 0);
        try {
            if (buildingIds == null || buildingIds.isEmpty()) {
                return new ArrayList<>();
            }
            
            // 查询指定楼栋下的所有单元ID
            LambdaQueryWrapper<Unit> queryWrapper = new LambdaQueryWrapper<>();
            queryWrapper.select(Unit::getId);
            queryWrapper.in(Unit::getBuildingId, buildingIds);
            queryWrapper.eq(Unit::getDeleted, 0);
            
            List<Unit> units = this.list(queryWrapper);
            List<Long> unitIds = units.stream()
                    .map(Unit::getId)
                    .collect(Collectors.toList());
            
            log.info("根据楼栋ID集合获取单元ID集合成功，楼栋数量：{}，单元数量：{}", buildingIds.size(), unitIds.size());
            return unitIds;
        } catch (Exception e) {
            log.error("根据楼栋ID集合获取单元ID集合失败，楼栋IDs：{}", buildingIds, e);
            return new ArrayList<>();
        }
    }

    @Override
    public List<Long> getUnitIdsByBuildingId(Long buildingId) {
        log.info("根据楼栋ID获取单元ID列表，楼栋ID：{}", buildingId);
        try {
            if (buildingId == null) {
                return new ArrayList<>();
            }
            
            // 查询指定楼栋下的所有单元ID
            LambdaQueryWrapper<Unit> queryWrapper = new LambdaQueryWrapper<>();
            queryWrapper.select(Unit::getId);
            queryWrapper.eq(Unit::getBuildingId, buildingId);
            queryWrapper.eq(Unit::getDeleted, 0);
            
            List<Unit> units = this.list(queryWrapper);
            List<Long> unitIds = units.stream()
                    .map(Unit::getId)
                    .collect(Collectors.toList());
            
            log.info("根据楼栋ID获取单元ID列表成功，楼栋ID：{}，单元数量：{}", buildingId, unitIds.size());
            return unitIds;
        } catch (Exception e) {
            log.error("根据楼栋ID获取单元ID列表失败，楼栋ID：{}", buildingId, e);
            return new ArrayList<>();
        }
    }

    /**
     * 根据社区ID获取楼栋ID列表
     * @param communityId 社区ID
     * @return 楼栋ID列表
     */
    private List<Long> getBuildingIdsByCommunityId(Long communityId) {
        log.info("根据社区ID获取楼栋ID列表，社区ID：{}", communityId);
        try {
            if (communityId == null) {
                return new ArrayList<>();
            }
            
            // 查询指定社区下的所有楼栋ID
            LambdaQueryWrapper<Building> queryWrapper = new LambdaQueryWrapper<>();
            queryWrapper.select(Building::getId);
            queryWrapper.eq(Building::getCommunityId, communityId);
            queryWrapper.eq(Building::getDeleted, 0);
            
            List<Building> buildings = buildingMapper.selectList(queryWrapper);
            List<Long> buildingIds = buildings.stream()
                    .map(Building::getId)
                    .collect(Collectors.toList());
            
            log.info("根据社区ID获取楼栋ID列表成功，社区ID：{}，楼栋数量：{}", communityId, buildingIds.size());
            return buildingIds;
        } catch (Exception e) {
            log.error("根据社区ID获取楼栋ID列表失败，社区ID：{}", communityId, e);
            return new ArrayList<>();
        }
    }

    /**
     * 根据社区ID集合获取楼栋ID列表
     * @param communityIds 社区ID集合
     * @return 楼栋ID列表
     */
    private List<Long> getBuildingIdsByCommunityIds(List<Long> communityIds) {
        log.info("根据社区ID集合获取楼栋ID列表，社区数量：{}", communityIds != null ? communityIds.size() : 0);
        try {
            if (communityIds == null || communityIds.isEmpty()) {
                return new ArrayList<>();
            }
            
            // 查询指定社区下的所有楼栋ID
            LambdaQueryWrapper<Building> queryWrapper = new LambdaQueryWrapper<>();
            queryWrapper.select(Building::getId);
            queryWrapper.in(Building::getCommunityId, communityIds);
            queryWrapper.eq(Building::getDeleted, 0);
            
            List<Building> buildings = buildingMapper.selectList(queryWrapper);
            List<Long> buildingIds = buildings.stream()
                    .map(Building::getId)
                    .collect(Collectors.toList());
            
            log.info("根据社区ID集合获取楼栋ID列表成功，社区数量：{}，楼栋数量：{}", communityIds.size(), buildingIds.size());
            return buildingIds;
        } catch (Exception e) {
            log.error("根据社区ID集合获取楼栋ID列表失败，社区IDs：{}", communityIds, e);
            return new ArrayList<>();
        }
    }

    /**
     * 应用数据权限过滤
     * 根据《智慧社区微服务架构总览.md》权威标准实现
     */
    private void applyDataPermissionFilter(LambdaQueryWrapper<Unit> queryWrapper) {
        try {
			// 获取当前用户信息
			DataScopeInfo uds = dataScopeFeign.getUserDataScope(SecurityUtils.getCurrentUserId());
            
            // 超级管理员跳过数据权限过滤
            if (uds.isSuperAdmin()) {
                return;
            }
            
            // 检查用户是否有关联物业公司
            if (!uds.isPropertyCompanyUser()) {
                queryWrapper.eq(Unit::getId, -1L);
                return;
            }
            
            // 获取用户可访问的社区ID集合
            List<Long> communityIds = uds.getCommunityIds();
            if (communityIds.isEmpty()) {
                queryWrapper.eq(Unit::getId, -1L);
                return;
            }
            
            // 获取用户可访问的楼栋ID集合
            List<Long> buildingIds = getBuildingIdsByCommunityIds(communityIds);
            if (buildingIds.isEmpty()) {
                queryWrapper.eq(Unit::getId, -1L);
                return;
            }
            
            // 应用楼栋权限过滤
            queryWrapper.in(Unit::getBuildingId, buildingIds);
        } catch (Exception e) {
            log.error("应用数据权限过滤失败", e);
            queryWrapper.eq(Unit::getId, -1L); // 异常时返回空结果
        }
    }
}
